<script lang="ts" setup>
import type { OrderItem } from '@/types/api/order'
import type { Ref } from 'vue'
import { orderApi } from '@/request/api'
import { useGlobalCache } from '@/stores'
import { useDict } from '@/stores/index'
import { useConsole, useNav } from '@/utils'
import {
  handleChaKanZhangDan,
  handleDingSunJieGuo,
  handleFengKongBuLu,
  handleFuWuBaoZhang,
  handleLianXiShangJia,
  handleMaiDuan,
  handleQianChengNuoShu,
  handleQianShouDan,
  handleQianShuDaiKou,
  handleQianShuHeTong,
  handleQianShuHeTong_JunZiQian,
  handleQueRenShouHuo,
  handleQuXiaoDingDan,
  handleRenLianShenHe,
  handleShenQingGuiHuan,
  handleShenQingTuiKuan,
  handleShouHuoBuLu,
  handleWeiYueJin,
} from '@/utils/order-operation'
import { useOrderStatusCheck } from '@/utils/order-status-check'
import { to } from 'await-to-js'
import { isEmpty, isNil, omit } from 'lodash-es'
import {
  computed,
  onBeforeUnmount,
  onMounted,
  reactive,
  ref,
} from 'vue'

interface NewOrderItem extends OrderItem {
  /** 当前期 */
  _currentTerm?: number
  /** 当期应付款 */
  _currentTermAmount?: number
}

const props = defineProps<{
  item: NewOrderItem
}>()
const inDev = INDEV
const pending = reactive({
  refresh: false,
})
const dict = useDict()
const refreshDetail = ref() as Ref<NewOrderItem>
const detail = computed(() => {
  // return refreshDetail.value || props.item
  return Object.assign(
    { ...props.item },
    omit(refreshDetail.value, [
      'extraInfo',
      'haveOverdueFine',
      'productOrderExtra',
      'installmentAmount',
    ]),
  )
})
const packageName = computed(() => {
  return detail.value.params.detail
    .split(' ')
    .map((part, index) =>
      index === 0 ? dict.operateDict(part)?.itemText ?? part : part,
    )
    .join(' ')
})
const orderStatus = computed(() => {
  if (detail.value.subStatus === 201) {
    return {
      0: '待签约',
      100: '请签约',
      101: '签约确认中',
      200: '请签约',
      201: '签约确认中',
    }[detail.value.agreement]
  }
  return {
    101: UNI_PLATFORM === 'mp-kuaishou' ? '请支付首期' : '请支付押金',
    102: '请录入审批资料',
    103: '审核中',
    104: '审批中',
    105: '审批中',
    201: '请签约',
    202: '请提交录单材料',
    203: '材料审核中',
    204: '待发货',
    205: '请点击收货',
    301: '待归还',
    302: '归还中',
    401: '已关闭',
    402: '已买断',
    403: '交易完成',
  }[detail.value.subStatus]
})
onMounted(() => {
  uni.$on('refreshSpecificOrderItem', refreshSelf)
  uni.$on('refreshOrderItems', () => refreshSelf(detail.value.id))
})

onBeforeUnmount(() => {
  uni.$off('refreshSpecificOrderItem')
  uni.$off('refreshOrderItems')
})

async function refreshSelf(oid: NewOrderItem['id']) {
  if (detail.value.id !== oid) {
    return
  }

  // const [err, res] = await to(orderApi.detail(oid))
  pending.refresh = true
  const [err, res] = await to(
    orderApi.page({
      id: detail.value.id,
      pageNo: 1,
      pageSize: 1,
      status: -1,
    }),
  )
  pending.refresh = false
  if (err || isEmpty(res.data)) {
    return
  }

  const data = { ...res.data[0] } as NewOrderItem
  if (!isEmpty(data.productOrderRecordVoList)) {
    data._currentTerm = data.productOrderRecordVoList.filter(
      y => y.payment === 1,
    ).length
    data._currentTermAmount = data.productOrderRecordVoList.find(
      y => y.payment === 0,
    )?.price
  }
  refreshDetail.value = data
  // useConsole?.log(JSON.stringify(data))
}

function handleNavDetail() {
  useGlobalCache().currentOrderId = detail.value.id

  useNav('/order/detail', { oid: detail.value.id })
}

function handleConsole() {
  useConsole?.log('item', detail.value)
  // useConsole?.log('item', JSON.stringify(detail.value))
}
</script>

<template>
  <view class="relative rd-16px bg-white">
    <view v-if="inDev" class="absolute left-0 top-0 z-1 p-4px">
      <view
        class="grid grid-cols-[auto_auto] gap-x-10px gap-y-4px bg-[purple] px-10px py-6px text-26px text-white"
      >
        <view class="op-50">OID</view>
        <view>{{ item.id }}</view>
        <view class="op-50">TYPE</view>
        <view>{{ item.extraInfo.type }}</view>
        <view class="op-50">SUBSTA</view>
        <view>{{ item.subStatus }}</view>
      </view>
    </view>

    <view v-if="pending.refresh" class="absolute right-0 top-0 z-1 p-14px">
      <div class="text-theme-primary i-svg-spinners:pulse-2 text-40px"></div>
    </view>
    <!--  -->
    <view @longpress="handleConsole">
      <ui-aspect-ratio>
        <image
          class="h-full w-full rd-16px"
          :src="detail.params.image"
          mode="aspectFit"
          @click="handleNavDetail"
        ></image>
      </ui-aspect-ratio>
    </view>

    <!--  -->
    <view class="mt-20px pl-40px">
      <view @click="handleNavDetail">
        <view class="flex">
          <view
            class="mr-20px h-50px flex-1 overflow-hidden text-30px text-#3 font-500 lh-50px"
          >{{ detail.params.title }}</view>
          <!-- <view class="shrink-0 rd-l-full bg-theme-primary pl-20px pr-20px text-28px text-white lh-50px">{{ orderStatus[detail.status] }}</view> -->
          <view
            class="bg-theme-primary shrink-0 rd-l-full pl-20px pr-20px text-28px text-white lh-50px"
          >{{ orderStatus }}</view>
        </view>

        <view
          v-if="detail.subStatus === 102 && !isEmpty(detail.riskRejectReason)"
          class="mt-20px pr-40px text-24px text-[red] lh-[1.5]"
        >
          <text class="font-500">材料驳回：</text>
          {{ detail.riskRejectReason }}
        </view>

        <view class="mt-20px pr-40px text-24px">
          <view class="grid grid-cols-[auto_1fr] gap-x-10px">
            <view class="text-#6a">套餐:</view>
            <view class="text-#3">{{ packageName }}</view>
          </view>
          <view class="grid grid-cols-[auto_1fr] mt-20px gap-x-10px">
            <view class="text-#6a">租期:</view>
            <view class="flex text-#3">
              <view class="text-theme-red">已还&thinsp;{{ detail?._currentTerm ?? "-" }}</view>
              <view class="">&thinsp;/&thinsp;{{ detail.leaseTerm }}&thinsp;期</view>
            </view>
          </view>
          <view class="flex justify-between">
            <view class="grid grid-cols-[auto_1fr] mt-20px gap-x-10px">
              <view class="text-#6a">下期租金:</view>
              <view class="text-theme-red">￥{{
                isNil(detail._currentTermAmount)
                  ? "-"
                  : (detail._currentTermAmount / 100).toFixed(2)
              }}</view>
            </view>
            <!-- <view class="grid grid-cols-[auto_1fr] mt-20px gap-x-10px">
              <view class="text-#6a">总租金:</view>
              <view class="text-theme-red">￥{{ (detail.params.model.price / 100).toFixed(2) }}</view>
            </view> -->
          </view>
        </view>
      </view>
    </view>

    <!--  -->
    <view class="py-40px">
      <view class="h-60px overflow-y-hidden">
        <scroll-view class="h-80px whitespace-nowrap" scroll-x>
          <view class="btn-group mx-40px inline-block shrink-0">
            <view class="min-w-610px flex gap-x-8px">
              <template v-if="useOrderStatusCheck.quZhiFu(detail)">
                <cm-pay-btn :id="detail.id" pay-title="去支付" pay-status="4">
                  <template #name>
                    <view class="btn btn-primary-black">去支付</view>
                  </template>
                </cm-pay-btn>
              </template>
                  <template v-if="useOrderStatusCheck.maiDuan(detail)">
                <!-- <view
                  class="btn btn-secondary-theme"
                  @click="handleMaiDuan({ oid: detail.id })"
                >买断</view> -->
                <cm-pay-btn :id="detail.id" pay-title="去支付" pay-status="6">
                  <template #name>
                    <view class="btn btn-primary-black">买断</view>
                  </template>
                </cm-pay-btn>
              </template>
              <template v-if="useOrderStatusCheck.renLianShenHe(detail)">
                <view
                  class="btn btn-primary-black"
                  @click="handleRenLianShenHe({ oid: detail.id })"
                >人脸审核</view>
              </template>
              <template v-if="useOrderStatusCheck.qianShuHeTong(detail)">
                <view
                  class="btn btn-primary-black"
                  @click="
                    handleQianShuHeTong({
                      oid: detail.id,
                      contractSignflow: detail.contractSignflow,
                    })
                  "
                >
                  {{ "签署合同" }}
                  <view
                    v-if="inDev"
                    class="absolute left-0px top-0px h-10px w-10px rd-full bg-[red]"
                  ></view>
                </view>
              </template>
              <template
                v-if="useOrderStatusCheck.qianShuHeTong_JunZiQian(detail)"
              >
                <view
                  class="btn btn-primary-black"
                  @click="handleQianShuHeTong_JunZiQian({ oid: detail.id })"
                >
                  {{ "签署合同" }}
                  <view
                    v-if="inDev"
                    class="absolute left-0px top-0px h-10px w-10px rd-full bg-[blue]"
                  ></view>
                </view>
              </template>
              <template v-if="useOrderStatusCheck.daiFengKongLuRu(detail)">
                <view
                  class="btn btn-primary-theme !w-160px !text-22px"
                  @click="
                    handleFengKongBuLu({ oid: detail.id, mode: detail.mode })
                  "
                >录入审批材料</view>
              </template>
              <template v-if="useOrderStatusCheck.daiShouHuoLuRu(detail)">
                <view
                  class="btn btn-primary-theme !w-160px !text-22px"
                  @click="
                    handleShouHuoBuLu({
                      oid: detail.id,
                      mode: detail.mode,
                      type: detail.extraInfo.type,
                    })
                  "
                >提交录单材料</view>
              </template>
              <template v-if="useOrderStatusCheck.qianShouDan(detail)">
                <view
                  class="btn btn-primary-black"
                  @click="handleQianShouDan({ oid: detail.id })"
                >签收单</view>
              </template>
              <template v-if="useOrderStatusCheck.qianChengNuoShu(detail)">
                <view
                  class="btn btn-primary-black"
                  @click="handleQianChengNuoShu({ oid: detail.id })"
                >签承诺书</view>
              </template>
              <template v-if="useOrderStatusCheck.qianShuDaiKou(detail)">
                <view
                  class="btn btn-primary-black"
                  @click="handleQianShuDaiKou({ oid: detail.id })"
                >签署代扣</view>
              </template>

              <template v-if="useOrderStatusCheck.chaKanZhangDan(detail)">
                <view
                  class="btn btn-secondary-theme"
                  @click="handleChaKanZhangDan({ oid: detail.id })"
                >查看账单</view>
              </template>
              <!-- <template v-if="useOrderStatusCheck.shouHouXiangQing(detail)">
                <view class="btn btn-secondary-theme" @click="handleShouHouXiangQing({ oid: detail.id })">售后详情</view>
              </template> -->
              <template v-if="useOrderStatusCheck.queRenShouHuo(detail)">
                <view
                  class="btn btn-secondary-theme"
                  @click="handleQueRenShouHuo({ oid: detail.id })"
                >确认收货</view>
              </template>
              <!-- <template v-if="useOrderStatusCheck.ziTi(detail)">
                <view class="btn btn-secondary-theme" @click="handleZiTi({ shopInfo: detail.shopsVo })">自提</view>
              </template> -->
              <!-- <template v-if="useOrderStatusCheck.queRenZiTi(detail)">
                <view class="btn btn-secondary-theme" @click="handleQueRenZiTi({ oid: detail.id })">确认自提</view>
              </template> -->
              <template v-if="useOrderStatusCheck.shenQingGuiHuan(detail)">
                <view
                  class="btn btn-secondary-theme"
                  @click="handleShenQingGuiHuan({ oid: detail.id })"
                >申请归还</view>
              </template>
              <template v-if="useOrderStatusCheck.dingSunJieGuo(detail)">
                <view
                  class="btn btn-secondary-theme"
                  @click="handleDingSunJieGuo({ oid: detail.id })"
                >定损结果</view>
              </template>
              <template v-if="useOrderStatusCheck.weiYueJin(detail)">
                <view
                  class="btn btn-secondary-theme"
                  @click="handleWeiYueJin({ oid: detail.id })"
                >违约金</view>
              </template>
              <!-- <template v-if="useOrderStatusCheck.xuZu(detail)">
                <view class="btn btn-secondary-theme" @click="handleXuZu({ oid: detail.id })">续租</view>
              </template> -->
          
              <template v-if="useOrderStatusCheck.quXiaoDingDan(detail)">
                <view
                  class="btn btn-secondary-theme"
                  @click="handleQuXiaoDingDan({ oid: detail.id })"
                >取消订单</view>
              </template>
              <template v-if="useOrderStatusCheck.shenQingTuiKuan(detail)">
                <view
                  class="btn btn-secondary-theme"
                  @click="handleShenQingTuiKuan({ oid: detail.id })"
                >申请退款</view>
              </template>
              <template v-if="useOrderStatusCheck.fuWuBaoZhang(detail)">
                <view
                  class="btn btn-primary-theme"
                  @click="handleFuWuBaoZhang({ oid: detail.id })"
                >服务保障</view>
              </template>
              <view
                class="btn btn-secondary-theme"
                @click="handleLianXiShangJia()"
              >联系商家</view>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<style lang="less" scoped>
.btn-group {
  .btn {
    --uno: 'shrink-0 relative';
    width: 146.5rpx;
    line-height: 60rpx;
    height: 60rpx;
    font-size: 26rpx;

    &.btn-secondary-theme {
      line-height: 56rpx;
    }
  }
}
</style>
